import 'dart:core';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:hxdj/common/my_header_global.dart';

class MyMenuItem {
  late String? title; // 菜单标题
  MyMenuItem(this.title);
}

class MyPopupMenu {
  static late BuildContext context;

  late Rect attachRect;

  late Size? _screenSize;

  late OverlayEntry _entry;

  late double arrowHeight;

  late MyMenuItem menuItem;

  late bool isShow = false;
  MyPopupMenu({BuildContext? context, MyMenuItem? item}) {
    menuItem = item ?? MyMenuItem("");
    arrowHeight = 10;
    if (context != null) {
      MyPopupMenu.context = context;
    }
  }

  void show({Rect? rect, required GlobalKey widgetKey, MyMenuItem? item}) {
    if (isShow) return;
    isShow = true;
    menuItem = item ?? menuItem;
    attachRect = rect ?? MyPopupMenu().getWidgetGlobalRect(widgetKey);
    _screenSize = window.physicalSize / window.devicePixelRatio;

    _LayoutP layoutp = _calculateOffset(
      context,
      attachRect,
      102,
      45,
    );

    // OverlayEntry overlayEntry = OverlayEntry(
    //   builder: (BuildContext context) {
    //     return Positioned(
    //       // 设置位置，这里使用中心位置
    //       // left: MediaQuery.of(context).size.width / 2 - 100, // 宽度的一半减去内容宽度的一半
    //       // top: MediaQuery.of(context).size.height / 2 - 50, // 高度的一半减去内容高度的一半
    //       width: 200, // 设定宽度
    //       height: 100, // 设定高度
    //       child: Material(
    //         elevation: 4.0,
    //         child: Container(
    //           padding: const EdgeInsets.all(8.0),
    //           color: Colors.blue.withOpacity(0.5), // 半透明背景
    //           child: Center(
    //             child: Text('这是一个弹框内容', style: TextStyle(color: Colors.white)),
    //           ),
    //         ),
    //       ),
    //     );
    //   },
    // );

    // // 将 OverlayEntry 添加到 Overlay 中
    // Overlay.of(context).insert(overlayEntry);
    debugPrint("attachRect: $attachRect");
    _entry = OverlayEntry(builder: (context) {
      return Positioned(left: layoutp.offset.dx, top: layoutp.offset.dy, width: 102, height: 55, child: build(layoutp));
    });

    Overlay.of(context).insert(_entry);
  }

  Widget build(_LayoutP layoutp) {
    return GestureDetector(
      onTap: () {
        _entry.remove();
      },
      child: Material(
          child: Container(
        color: Colors.transparent,
        child: Stack(
          children: <Widget>[
            // triangle arrow
            // Positioned(
            //   // left: layoutp.attachRect.left + layoutp.attachRect.width / 2.0,
            //   left: layoutp.attachRect.left + layoutp.attachRect.width / 2.0,
            //   top: layoutp.isDown ? layoutp.offset.dy + layoutp.height : layoutp.offset.dy - arrowHeight,
            //   child: CustomPaint(
            //     size: Size(15.0, arrowHeight),
            //     painter: TrianglePainter(isDown: layoutp.isDown, color: Colors.yellow),
            //   ),
            // ),
            // menu content
            Positioned(
              top: 10,
              child: Container(
                child: const MyImage(
                  imageName: "ic_vip_tip",
                  width: 102,
                  height: 45,
                  boxFit: BoxFit.fitWidth,
                ),
              ),
            ),
            Positioned(
                top: 17,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 5),
                  alignment: Alignment.center,
                  child: Text("开通VIP再下单\n本单最高可省1592.6元",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: MyColours.materialBg, fontSize: 8.sp, fontWeight: FontWeight.w600)),
                )),
          ],
        ),
      )),
    );
  }

  /// 计算布局位置
  _LayoutP _calculateOffset(
    BuildContext context,
    Rect attachRect,
    double contentWidth,
    double contentHeight,
  ) {
    double dx = attachRect.left + attachRect.width / 2.0 - contentWidth / 2.0;
    if (dx < 10.0) {
      dx = 10.0;
    }

    if (dx + contentWidth > _screenSize!.width && dx > 10.0) {
      double tempDx = _screenSize!.width - contentWidth - 10;
      if (tempDx > 10) {
        dx = tempDx;
      }
    }

    double dy = attachRect.top - contentHeight;
    bool isDown = false;
    if (dy <= MediaQuery.of(context).padding.top + 10) {
      // The have not enough space above, show menu under the widget.
      dy = arrowHeight + attachRect.height + attachRect.top;
      isDown = false;
    } else {
      dy -= arrowHeight;
      isDown = true;
    }

    return _LayoutP(
      width: contentWidth,
      height: contentHeight,
      attachRect: attachRect,
      offset: Offset(dx, dy),
      isDown: isDown,
    );
  }

  dismiss() {
    _entry.remove();
    isShow = false;
  }

  Rect getWidgetGlobalRect(GlobalKey key) {
    RenderBox renderBox = key.currentContext!.findRenderObject() as RenderBox;
    var offset = renderBox.localToGlobal(Offset.zero);

    debugPrint("offset: $offset");
    debugPrint("renderBox: ${renderBox.size}");

    return Rect.fromLTWH(offset.dx, offset.dy, renderBox.size.width, renderBox.size.height);
  }
}

class _LayoutP {
  double width;
  double height;
  Offset offset;
  Rect attachRect;
  bool isDown;

  _LayoutP({
    required this.width,
    required this.height,
    required this.offset,
    required this.attachRect,
    required this.isDown,
  });
}

// 画弹出菜单下面的三角形
class TrianglePainter extends CustomPainter {
  bool isDown;
  Color color;

  TrianglePainter({
    this.isDown = true,
    this.color = const Color.fromARGB(0, 0, 0, 0),
  });

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.strokeWidth = 2.0;
    paint.color = color;
    paint.style = PaintingStyle.fill;

    Path path = Path();
    if (isDown) {
      path.moveTo(0.0, -1.0);
      path.lineTo(size.width, -1.0);
      path.lineTo(size.width / 2.0, size.height);
    } else {
      path.moveTo(size.width / 2.0, 0.0);
      path.lineTo(0.0, size.height + 1);
      path.lineTo(size.width, size.height + 1);
    }

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

// import 'package:flutter/material.dart';
// import 'package:flutter/rendering.dart';

// void main() {
//   runApp(MyApp());
// }

// class MyApp extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       home: Scaffold(
//         appBar: AppBar(
//           title: Text('Flutter Popup Example'),
//         ),
//         body: Center(
//           child: MyPopupButton(),
//         ),
//       ),
//     );
//   }
// }

// class MyPopupButton extends StatefulWidget {
//   @override
//   _MyPopupButtonState createState() => _MyPopupButtonState();
// }

// class _MyPopupButtonState extends State<MyPopupButton> with SingleTickerProviderStateMixin {
//   late OverlayEntry _overlayEntry;
//   OverlayState? _overlayState;

//   void _showOverlay(BuildContext context, Offset position) {
//     _overlayEntry = _overlayState!.insert(
//       OverlayEntry(
//         builder: (context) => Positioned(
//           left: position.dx,
//           top: position.dy + 50, // Adjust the position based on your button size
//           width: 100,
//           height: 100,
//           child: CustomPaint(
//             painter: TriangleGradientPainter(),
//           ),
//         ),
//       ),
//     );
//   }

//   void _removeOverlay() {
//     _overlayEntry.remove();
//   }

//   @override
//   Widget build(BuildContext context) {
//     _overlayState = Overlay.of(context);
//     return GestureDetector(
//       onTap: () {
//         RenderBox renderBox = context.findRenderObject() as RenderBox;
//         var size = renderBox.size;
//         var localPosition = renderBox.localToGlobal(Offset.zero);
//         var position = localPosition + Offset(size.width / 2, size.height); // Center the popup below the button
//         _showOverlay(context, position);
//         Future.delayed(Duration(seconds: 2), _removeOverlay); // Remove the overlay after 2 seconds
//       },
//       child: Container(
//         padding: EdgeInsets.all(16.0),
//         decoration: BoxDecoration(
//           border: Border.all(color: Colors.blueAccent, width: 2.0),
//           borderRadius: BorderRadius.circular(8.0),
//         ),
//         child: Text(
//           'Tap Me',
//           style: TextStyle(fontSize: 20.0, color: Colors.blueAccent),
//         ),
//       ),
//     );
//   }

//   @override
//   void dispose() {
//     _removeOverlay();
//     super.dispose();
//   }
// }

// class TriangleGradientPainter extends CustomPainter {
//   @override
//   void paint(Canvas canvas, Size size) {
//     var paint = Paint()
//       ..shader = LinearGradient(
//         begin: Alignment.topLeft,
//         end: Alignment.bottomRight,
//         colors: [Colors.red, Colors.blue],
//       ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
//     var path = Path();
//     path.moveTo(size.width / 2, 0);
//     path.lineTo(size.width, size.height);
//     path.lineTo(0, size.height);
//     path.close();
//     canvas.drawPath(path, paint);
//   }

//   @override
//   bool shouldRepaint(CustomPainter oldDelegate) {
//     return oldDelegate != this;
//   }
// }
